
<template>
	<eui-background type="common" class="lowcode-custom-sql-page-wrap">
		<view class="lowcode-nav-wrap">
			<eui-nav-bar :title="state?.title || '弹框选择'" color="#333"  />
			<eui-search-bar ref="searcBarRef" radius="100" showFilter placeholder="请输入搜索内容" @clear="handleClearSearch" @confirm="handleEnterSearch" >
				<template #searchFields>
					<view class="lowcode-components-wrap">
						<view v-for="(colField, idx) in state?.searchItems" :key="idx" class="lowcode-components-item">
							<DynamicComponent :conf-object="colField" :data-object="state.searchCardData" parentSrc="1" @handleDynamicChange="handleSearchDynamicChange" :md-code="state.mdCode || ''" />
						</view>
					</view>
					<view class="lowcode-popup-bottom flex-1 flex">
						<eui-button type="max2" title="重置" singleTag="重置" @buttonClick="handlePopupClose"></eui-button>
						<eui-button type="max" title="确认" singleTag="确认" @buttonClick="handlePopupClose"></eui-button>
					</view>
				</template>
			</eui-search-bar>
		</view>
		<scroll-view scroll-y :refresher-enabled='true' :refresher-triggered="scrollTriggerd" @refresherrefresh="handleScrollRefresh"
			@scrolltolower="handleScrolltolower" :style="state.scrollViewStyle" >
			<radio-group v-if="state.IsMult !== '是'" @change="radioChange">
				<label class="uni-list-cell uni-list-cell-pd" v-for="(rowData, index) in state.listData" :key="rowData.value" :style="state.listitemStyle" >
					<view><radio :value="rowData?.[state.returnId || '']"  /></view>
					<view class="WTF">{{ '[' + rowData?.[state.returnId || ''] + ']' + rowData?.[state.returnName || ''] }}</view>
				</label>
			</radio-group>
			<checkbox-group v-if="state.IsMult === '是'" @change="checkboxChange">
				<label class="uni-list-cell uni-list-cell-pd" v-for="(rowData, index) in state.listData" :key="rowData.value" :style="state.listitemStyle" >
					<view><checkbox  :value="rowData?.[state.returnId || '']"  /></view>
					<view class="WTF">{{ '[' + rowData?.[state.returnId || ''] + ']' + rowData?.[state.returnName || ''] }}</view>
				</label>
			</checkbox-group>
		</scroll-view>
		<view class="lowcode-page-btm-btns-wrap flex-1 flex">
			<eui-button type="max2" title="取消" singleTag="取消" @buttonClick="handleCancel" ></eui-button>
			<eui-button type="max" title="确定" singleTag="确定" @buttonClick="handleConfirm" ></eui-button>
		</view>
	</eui-background>
</template>

<script setup lang="ts" >
import { ref, watch } from "vue";
import { onLoad, onReady, onShow } from "@dcloudio/uni-app";

import store from '@/store';
import useService from "@/hooks/useService";
import serviceTools from '@/common/service';

import DynamicComponent from "../dynamicComponent/index.vue";
import useLowcodeSystemInfo from "../hooks/useSystemInfo";
import type { LowCodePagination, LowcodeRect, LowCodeWhereListItem } from "../interface";
import type { LowcodeCustomSelectExtendParam, LowcodeCustomSelectReturn, LowcodeCustomSQLState } from "./interface";
import type { FetchMdBillListDataProxy } from "../billList/interface";
import { LOWCODERUNTIMEUNIQUEKEY } from "../constant";

const scrollTriggerd = ref<boolean>(false);
const searcBarRef = ref();
const state = ref<LowcodeCustomSQLState>({ listData: [], listitemStyle: { display: "flex", backgroundColor: "#FFF", alignItems: "center" } });
const pagination = ref<LowCodePagination>({ CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 });
const service = useService({ prefix: "mainApi" });
const { getSystemInfo } = useLowcodeSystemInfo();

const handleCancel = () => {
  const fCode = state.value?.fCode || "";
  uni.navigateBack({ success: () => uni.$emit(`${fCode}ChangeCallBack`, {}) });
};

const handleConfirm = () => {
	console.log("save btn click");
	if (!state.value.selectedVal?.length) {
		return uni.showModal({ title: "提示", content: "请选择数据！", showCancel: false, success: (res) => {} });
	}
	const retIdAry: string[] = [], retNameAry: string[] = [];
  const fCode = state.value?.fCode || "", retId = state.value?.returnId || "", retName = state.value?.returnName || "";
	state.value.selectedVal?.forEach(r => {
		retIdAry.push(r?.[retId]);
		retNameAry.push(r?.[retName]);
	});
  uni.navigateBack({ success: () => uni.$emit(`${fCode}ChangeCallBack`, { BackParms: { Key: retIdAry?.join(","), Value: retNameAry?.join(",") } }) });
};

const radioChange = (event: any) => {
	console.log("event?.detail?.value ", event?.detail?.value);
	const radioVal = event?.detail?.value, retId = state.value?.returnId || "";
	const radioRow = state.value.listData?.find(r => r?.[retId] === radioVal);
	state.value.selectedVal = [radioRow];
};

const checkboxChange = (event: any) => {
	console.log("event?.detail?.value ", event?.detail?.value);
	const checkboxVals = event?.detail?.value, retId = state.value?.returnId || "";
	const radioRows = state.value.listData?.filter(r => checkboxVals?.includes(r?.[retId]));
	state.value.selectedVal = radioRows;
};

const getScrollViewStyle = () => {
	const sysH = Math.ceil(state.value?.systemInfo?.windowHeight || 0);
	const navWrapH = Math.ceil(state.value?.navWrapRect?.height || 0);
	const btmWrapH = Math.ceil(state.value?.btmRect?.height || 0);
	const scrollH = (sysH >= (navWrapH + btmWrapH)) ? (sysH - (navWrapH + btmWrapH)) : 0;
	state.value.scrollViewStyle = { "background-color": "#f2f2f2", width: state.value?.systemInfo?.windowWidth + 'px', height: scrollH + 'px' };
};

const generateWhere = () => {
	let newWhereList: LowCodeWhereListItem[] = [];
	const searchVal = state.value.fuzzyVal;

	if (Array.isArray(state.value?.searchItems)) {
		searchVal && state.value?.searchItems?.forEach((item, idx) => {
			newWhereList.push({ c_left: idx === 0 ? "(" : "", c_col: item.fieldId, c_oper: "相似", c_value: searchVal, c_col_dtype: "System.String", c_logic: "或者", c_right: (idx + 1) === state.value?.searchItems?.length ? ")" : "" });
		});

		state.value?.searchItems?.forEach(item => {
			const iVal = state.value.searchCardData?.[item.fieldId || ""] || "";
			iVal && newWhereList.push({ c_left: "", c_col: item.fieldId, c_oper: "相似", c_value: iVal, c_col_dtype: "System.String", c_logic: "而且", c_right: "" });
		});
	}
	
	state.value.whereList = newWhereList;
	pagination.value = { CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 };
	uni.showLoading({ title: "查询中...", mask: true});
};

const handleSearchDynamicChange = async (key: string, newVal: any, oldVal: any, proxy?: { [key: string]: any }) => {
	if (!state.value.searchCardData) {
		state.value.searchCardData = {};
	}
	
	state.value.searchCardData[key] = newVal;
};

const handleEnterSearch = (proxy?: { value?: string }) => {
	// console.log("handleEnterSearch ", proxy?.value);
	const searchVal = proxy?.value || "";
	state.value.fuzzyVal = searchVal;
	generateWhere();
	fetchMdListData();
};

const handleClearSearch = () => {
	state.value.fuzzyVal = "";
	generateWhere();
	fetchMdListData();
};

const handlePopupClose = ({ singleTag }) => {
	if (singleTag === "重置") {
		if (!state.value.searchCardData) {
			state.value.searchCardData = {};
		}
		Array.isArray(state.value?.searchItems) && state.value?.searchItems?.forEach(item => state.value.searchCardData[item.fieldId || ""] = "");
	}
	if (singleTag === "确认") {
		generateWhere();
		fetchMdListData();
		searcBarRef.value?.closeDrawer?.();
	}
};

const handleScrollRefresh = () => {
	if (!scrollTriggerd) {
		return;
	}
	scrollTriggerd.value = true;
	pagination.value = { CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 };
	fetchMdListData();
};

const handleScrolltolower = () => {
	if ((pagination?.value?.CurrentPage || 0) >= (pagination?.value?.PageCount || 0)) {
		return
	}
	// pagination.value.CurrentPage = (pagination?.value?.CurrentPage || 1) + 1;
	pagination.value = { CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 };
	fetchMdListData();
};

const fetchMdListData = async (fetchProxy?: FetchMdBillListDataProxy) => {
	uni.showLoading({ title: "查询中...", mask: true});
	const sortColumns = (state.value.columns || [])?.filter(c => ["0", "1"].includes(c.sortDirection || ""));
	const fetchReq = {
		Sql: state.value.sql,
		TargetServiceName: state.value.service,
		WhereDatas: state.value?.whereList || [],
		RowData: { ...state.value?.recordData },
		SortColumns: sortColumns?.map(c => ({ ColumnId: c.columnId, Direction: c.sortDirection, SortIndex: c.sortIndex }))
	};
	const fetchReqProxy = { ModuleCode: state.value?.mdCode };
	const fetchRes = await service.request<LowcodeCustomSelectExtendParam, LowcodeCustomSelectReturn>(LOWCODERUNTIMEUNIQUEKEY, "FetchCustomSelectData", fetchReq, "", "", fetchReqProxy);
	scrollTriggerd.value = false;
	if (!fetchRes) {
		uni.hideLoading();
		return;
	}
	const cacheReturnObject = (Array.isArray(fetchRes?.RowItems) ? fetchRes?.RowItems : []);
	if (!pagination.value.fetchCount) {
		state.value.listData = cacheReturnObject;
		pagination.value = { ...pagination.value, RowsCount: cacheReturnObject?.length, PageCount: 1, fetchCount: 1 };
	} else {
		pagination.value.fetchCount = pagination.value.fetchCount + 1;
		state.value.listData = (state.value.listData || [])?.concat(cacheReturnObject);
	}
	uni.hideLoading();
	console.log("handleLowCodePage fetchMdListData == =", state.value);

	if (fetchProxy?.isOnLoad) {
		const userInfoPage = uni.createSelectorQuery().select(".lowcode-nav-wrap");
		userInfoPage.boundingClientRect(rect => {
			(state.value.navWrapRect = (rect as LowcodeRect));
			const btmElem = uni.createSelectorQuery().select(".lowcode-page-btm-btns-wrap");
			btmElem.boundingClientRect(btmRect => (state.value.btmRect = (btmRect as LowcodeRect))).exec();

			getScrollViewStyle();
		}).exec();
	}
};

const handleLowCodePage = async (proxy?: FetchMdBillListDataProxy) => {
	const dialogCFG = store?.state?.value?.lowcode?.dialogCFG;
	const filterColumns = dialogCFG?.columns?.filter(c => c.columnHide !== "1");  // TODO 查询条件 没有标题 c_title
	const searchItems = dialogCFG?.searchItems?.map(s => ({ ...s, c_code: s.fieldId, c_title: s.title, c_type: s.editMode }));
	state.value = { ...state.value, ...dialogCFG, columns: filterColumns, searchItems	};

	await fetchMdListData(proxy);
};

const handleSystemInfo = () => {
	const systemInfo = getSystemInfo();
	state.value.systemInfo = systemInfo;
};

onLoad((proxy) => {
  // console.log("store?.state?.value?.main?.loginInfo?.sUser;== =", store?.state?.value?.lowcode?.dialogCFG);
	handleSystemInfo();
	handleLowCodePage({ isOnLoad: true });
});
</script>

<style lang="scss" scoped>
@import '@/main.scss';
@import "../index.scss";

.uni-list-cell {
	font-size: 28rpx;
	padding: 20rpx 28rpx 20rpx 28rpx;
	border-bottom: solid 1rpx rgba(238, 238, 238, 1);
	line-height: 1;
}
</style>
